<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 16/4/1
 * Time: 上午9:23
 */
class ApiService extends Service {

    const API_KEY = '34GEDRRGD#@!FJY*';

    // 当前的服务器
    private $_server;

    public function __construct($server = 1){
        $this->_server = PubServer::getServerByPk($server);

        if(empty($this->_server)){
            exit('找不到服务器!');
        }
    }

    /**
     * Oss对接通用接口
     * @param $url          请求地址
     * @param $params       请求参数
     * @return array        统一格式返回
     *          - state             必带  成功返回true,错误返回false
     *          - data              可选  state为ture时有可能返回,数据
     *          - desc              可选  state为ture时有可能返回,列说明
     *          - totalNum          可选  state为true时有可能返回,列表总数
     *          - msg               可选  state为false是返回,错误信息
     *          - origin_result     必带  原始服务端返回数据
     * @throws CException
     */
    public function request($apiType, $params,$is_need_login = 1){
        $user = PubAuth::getUser();
        if(empty($user['Account']) && $is_need_login == 1){
            return array('state' => false, 'msg' => 'Not Login');
        }

        $domain = $this->getDomain();      
        $url = $domain . $apiType;
        
        $params = array_merge($params, array(
            'time'      => time(),
            'platform'  => PubRequest::R('p'),
            'serverid'  => $this->_server['develop_id'],
            'v'         => '3.0',
        	'key'		=> 'BF1A9DAFF92587A7FC93A6BB59230DA8',
        ));
//         echo "<pre>";
//         var_dump($params);
//         echo "</pre>";exit();
        ksort($params);
        $paramsStr = '';
        $paramsArr = array();
        foreach($params as $k=>$v){
            $paramsStr .= $k.$v;
            $paramsArr[] = "{$k}=".urlencode($v);
        }

        $flag = strtoupper(md5($paramsStr.self::API_KEY));
        $url = $url.'?'.implode('&', $paramsArr).'&flag='.$flag;

        // 记录请求日志
        Yii::log($url, CLogger::LEVEL_INFO, 'request.url');
        Yii::log($paramsStr.self::API_KEY, CLogger::LEVEL_INFO, 'request.flag');
        //echo $url;
        $re = PubFunc::request($url, array(), 10);
        self::doLog($user, $apiType, $params, $url, $re);
        
//         echo "<pre>";
//         var_dump($re);
//         echo "</pre>";exit;
        
        if($re['code'] != 200){
            // 如果http返回码不是200,则返回请求失败
            return array('state' => false, 'msg' => '请求失败', 'origin_result' => $re);
        }else{
	        //echo $re['code'];
            // json解码结果集
            $tmp = json_decode($re['result'], true);
	        //var_dump($tmp);
            // 错误码Key值默认选ret,兼容code
            $returnCode = isset($tmp['ret']) ? $tmp['ret'] : $tmp['code'];

            // 如果成功,则格式化数据返回
            if(isset($returnCode) && ($returnCode == 0)){
                $return = array('state' => true);

                // 可选返回参数
                $returnArr = array('data', 'desc', 'totalNum','msg');
                foreach($returnArr as $v){
                    if(isset($tmp[$v])){
                        $return[$v] = $tmp[$v];
                    }else if($v == 'data'){
                        $return['data'] = array();
                    }
                }

                // 请求的原始返回
                $return['origin_result'] = $re['result'];

                return $return;
            }else{
                return array('state' => false, 'msg' => $tmp['msg'], 'origin_result' => $re['result']);
            }
        }
    }

    public function doLog($user, $apiType, $params, $url, $re){
        $array = array(
            'user_id'       => $user['UserID'],
            'account'       => $user['Account'],
            'user_name'     => $user['UserName'],
            'type'          => $apiType,
            'params'        => is_array($params) ? json_encode($params) : $params,
            'url'           => $url,
            'return'        => is_array($re) ? json_encode($re) : $re,
            'create_time'   => time()
        );

        $model = new ModApiLog();
        $model->setAttributes($array, false);
        $model->save();
    }
    
    /**
     * 新增消息广播
     */
    public function sendBroadcast($params){
    	return $this->request('send_broadcast', $params);
    }
    
    /**
     * 道具/货币发送
     */
    public function sendGift($params){
    	return $this->request('send_person_item', $params,2);
    }
    
    /**
     * 全服道具/货币发送
     */
    public function sendGlobalMail($params){
    	return $this->request('send_global_item', $params);
    }
    
    /**
     * 全服邮件
     */
    public function sendNoticeMail($params){
    	return $this->request('send_mail_notice', $params);
    }
    
    /**
     * 踢人下线
     */
    public function kick($params){
    	return $this->request('kick_user', $params);
    }
    
    
    
    /**
     * 角色禁言
     */
    public function banChat($params){
    	return $this->request('shutup_user', $params);
    }

    /**
     * 账号封禁
     */
    public function ban($params){
    	return $this->request('ban_user', $params);
    }
    
    /**
     * 账号封禁(趣炫)
     */
    public function quxuan_ban($params){
    	return $this->request('quxuan_ban_user', $params,2);
    }
    
    /**
     * 获得账号信息
     * @param $account
     * @return array
     */
    public function roleInfo($params){
    	return $this->request('get_role_info', $params);
    }
    
    /**
     * 市场交易开关
     * @param $account
     * @return array
     */
    public function setMarketStatus($params){
    	return $this->request('set_market_status', $params);
    }
    
    /**
     * 白名单、内玩
     * 2白名单
     * 3内玩
     * 0正常
     * 1冻结
     * @param $account
     * @return array
     */
    public function setAccountStatus($params){
    	return $this->request('set_account_status', $params);
    }
    
    /**
     * 提供给趣炫使用
     * forbid(封号)/mute(禁言)/army_kickout(踢出帮派)
     * @param unknown $params
     */
    public function quxuanCommonSetting($params){
    	return $this->request('quxuan_common_setting', $params,2);
    }
    
    /**
     * 活动
     * @param unknown $params
     * @return Ambigous <multitype:, multitype:boolean string , multitype:boolean multitype: unknown , multitype:boolean unknown mixed , multitype:boolean string Ambigous <multitype:string , number, mixed> >
     */
    public function sendActivity($params){
    	return $this->request('holiday_activity_setting', $params);
    }
    
    /**
     * 同步热更趣炫    渠道 -- 专服 对应
     * @param unknown $params
     * @return Ambigous <multitype:, multitype:boolean string , multitype:boolean multitype: unknown , multitype:boolean unknown mixed , multitype:boolean string Ambigous <multitype:string , number, mixed> >
     */
    public function setQuxuanChannelServer($params){
    	return $this->request('set_quxuan_channel_server', $params);
    }
    
    /**
     * 同步热更趣炫    专服 -- key 对应表
     * @param unknown $params
     * @return Ambigous <multitype:, multitype:boolean string , multitype:boolean multitype: unknown , multitype:boolean unknown mixed , multitype:boolean string Ambigous <multitype:string , number, mixed> >
     */
    public function setQuxuanSpecialServer($params){
    	return $this->request('set_quxuan_special_server', $params);
    }
    
    
    
    /**
     * 这里以下的接口暂无使用且都不能使用的，还未进行开发的
     */
    
    
    /**
     * 17.帮派信息接口
     * @param $guildName
     * @return mixed
     */
    public function guildInfoList($guildName){
        $params = array(
            'guildName' => $guildName
        );

        return $this->request('guild_info_list', $params);
    }

    /**
     * 3.获取消息广播列表
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function broadcastList($startTime, $endTime){
        $params = array(
            'startTime' => $startTime,
            'endTime'   => $endTime
        );
        return $this->request('broadcast_list', $params);
    }

    

    /**
     * 获取广播消息
     * @param $id
     * @return array
     */
    public function getBroadcast($id){
        $params = array(
            'id' => $id
        );
        return $this->request('get_broadcast', $params);
    }

    /**
     * 删除广播接口
     * @param $id
     * @return array
     */
    public function deleteBroadcast($id){
        $params = array(
            'id' => $id
        );
        return $this->request('delete_broadcast', $params);
    }

    /**
     * 获得角色列表
     * @param $params
     */
    public function getRoleList($params){
        return $this->request('role_info_list', $params);
    }

    /**
     * 获得角色信息
     * @param $account
     * @return array
     */
    public function roleInfoDetails($search){
        $params = array('roleName' => $search, 'roleId' => $search);
        return $this->request('role_info_details', $params);
    }

    /**
     * 获得角色扩展信息
     * @param $roleId
     * @param $type
     * @return array
     */
    public function roleExtra($roleId, $type){
        $params = array(
            'type'   => $type,
            'roleId' => $roleId
        );
        return $this->request('user_extra_detail', $params);
    }

    /**
     * 获得账号信息
     * @param $account
     * @return array
     */
    public function accountInfo($account){
        $params = array('account' => $account);
        return $this->request('account_info_details', $params);
    }


    /**
     * 20.获取游戏公告列表
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function announcementList($startTime, $endTime){
        $params = array(
            'startTime' => $startTime,
            'endTime'   => $endTime
        );
        return $this->request('announcement_list', $params);
    }

    /**
     * 编辑游戏公告接口
     * @param $params
     * @return array
     */
    public function editAnnouncement($params){
        return $this->request('edit_announcement', $params);
    }

    /**
     * 获取游戏公告消息
     * @param $id
     * @return array
     */
    public function getAnnouncement($id){
        $params = array(
            'id' => $id
        );
        return $this->request('get_announcement', $params);
    }


    /**
     * 删除游戏公告接口
     * @param $id
     * @return array
     */
    public function deleteAnnouncement($id){
        $params = array(
            'id' => $id
        );
        return $this->request('delete_announcement', $params);
    }


    

    public function globalMailList($params){
        return $this->request('global_mail_list', $params);
    }

    
    public function deleteGlobalMail($id){
        $params = array(
            'id' => $id
        );
        return $this->request('del_global_mail', $params);
    }


    /**
     * 踢人下线
     * @param $params
     * @return array
     */
    public function clear($params){
        return $this->request('role_clear', $params);
    }

    /**
     * 扣道具
     * @param $params
     * @return array
     */
    public function delProp($params){
        return $this->request('del_prop', $params);
    }

    /**
     * 扣金币
     * @param $params
     * @return array
     */
    public function delGold($params){
        return $this->request('deduct_gold', $params);
    }

    public function getItem(){
        return $this->request('item_lists', array());
    }

    /**
     * 检查一个帐号是否在白名单内
     * @param $params
     * @return array
     */
    public function checkWhite($params){
        return $this->request('check_white_list', $params);
    }

    /**
     * 添加白名单
     * @param $params
     * @return array
     */
    public function addWhite($params){
        return $this->request('add_white_list', $params);
    }

    /**
     * 删除白名单
     * @param $params
     * @return array
     */
    public function delWhite($params){
        return $this->request('del_white_list', $params);
    }

    public function noticeMailList($params){
        return $this->request('get_mail_notice', $params);
    }

    

    public function deleteNoticeMail($id){
        $params = array(
            'id' => $id
        );
        return $this->request('del_mail_notice', $params);
    }

    public function getOnline(){
        return $this->request('get_online_num', array());
    }

    /**
     * 获得后端服务器API地址
     * @return mixed|null|string
     */
    private function getDomain(){
        if(empty($this->_server)) return '';

        return $this->_server['oss_api'];
    }

    /**
     * 交易取消
     * @param $params
     * @return mixed
     */
    public function auctionCancel($params){
        return $this->request('auction_punishment_cancel', $params);
    }

    /**
     * 材料冻结
     * @param $params
     * @return mixed
     */
    public function auctionFrozen($params){
        return $this->request('auction_punishment_frozen', $params);
    }

    /**
     * 屏蔽寄售功能
     * @param $params
     * @return mixed
     */
    public function auctionClose($params){
        return $this->request('auction_punishment_close_func', $params);
    }

    /**
     * 保证金扣除
     * @param $params
     * @return mixed
     */
    public function auctionBond($params){
        return $this->request('auction_punishment_bond', $params);
    }
}
